import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ICategoryItem, TopCategory, SubCategory } from '@/types/goods'
import { IResponse } from '@/types/data'
import { topCategory } from './constants'

const defaultCategory = topCategory.map(item => ({ name: item }))

export default defineStore('category', {
  state: () => ({
    list: defaultCategory as ICategoryItem[], //装分类数据的
    topCategory: {} as TopCategory,
    subCategory: {} as SubCategory,
  }),
  actions: {
    async getCategoryList() {
      const r = await request.get<IResponse<ICategoryItem[]>>('/home/category/head')
      console.log(r)
      this.list = r.data.result
      this.list.forEach(item => item.open = false)
    },
    open(id: string) {
      this.list.find(item => item.id === id)!.open = true
    },
    hide(id: string) {
      this.list.find(item => item.id === id)!.open = false
    },
    async getTopCategory(id: string) {
      const res = await request.get<IResponse<TopCategory>>('/category', {
        params: {
          id,
        },
      })
      this.topCategory = res.data.result
    },
    // sub
    async getSubFilter(id: string) {
      const res = await request.get<IResponse<SubCategory>>('/category/sub/filter', {
        params: {
          id,
        },
      })
      this.subCategory = res.data.result
    },
  }
})